<script setup lang='ts'>
import type { IAdd, IEdit, IList } from '@fl/api/anjutong/model/product-model'
import type { VxeGridInstance, VxeGridProps, VxePagerEvents } from 'vxe-table'

import { fsConfigGet, fsConfigUpdate, getLabelValue, productAdd, productDelete, productEdit, productList, updateStatusById } from '@fl/api/anjutong/index'

import EditForm from './edit-form.vue'

const formTypeEunm = {
    add: '新建',
    destroy: '删除',
    edit: '编辑',
} as const

type RowVO = {
    catName: string
    createTime: string
    financialName: string
    hits: string
    name: string
    num: string
    remark: string
    sort: string
    status: string
    view: string
}
const centerDialogVisible = ref(false)
const formType = ref('')
const dialogTitle = computed(() => {
    return `${formType.value}产品`
})
const state = ref({
    appId: '',
    banner: '',
    catId: '',
    code: '',
    creditLimit: 0,
    financialId: '',
    id: '',
    img: '',
    interestRate: 0,
    isDeleted: 0,
    linkType: '',
    linkUrl: '',
    name: '',
    remark: '',
    sort: 0,
    status: true,
    tag: '',
    type: '',
})
const columns = [
    {
        colProps: {
            span: 6,
        },
        label: '金融机构名称',
        prop: 'financialName',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '产品分类',
        options: async () => {
            const data = await getLabelValue(1)
            return data ?? []
        },
        prop: 'catId',
        valueType: 'select',
    },
]
const submitLoading = ref(false)
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const searchForm = ref({
    catId: '',
    financialName: '',
})
const xGrid = ref<VxeGridInstance<RowVO>>()
const gridOptions = reactive<VxeGridProps<RowVO>>({
    align: 'center',
    columnConfig: {
        resizable: true,
    },
    columns: [
        { title: '序号', type: 'seq', width: 50 },
        { field: 'name', title: '产品名称' },
        { field: 'catName', title: '产品分类' },
        { field: 'financialName', title: '金融机构名称' },
        { field: 'sort', title: '排序' },
        { field: 'createTime', title: '创建时间' },
        { field: 'view', title: '浏览量' },
        { field: 'hits', title: '点击量' },
        { field: 'num', title: '办理量' },
        { field: 'remark', title: '备注' },
        { field: 'status', slots: { default: 'status' }, title: '状态' },
        { slots: { default: 'operate' }, title: '操作', width: 200 },

    ],
    data: [],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 530,
    keepSource: true,
    loading: false,
    showOverflow: true,
})
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    findList()
}
async function findList() {
    gridOptions.loading = true
    try {
        const params: IList = {
            catId: searchForm.value.catId,
            financialName: searchForm.value.financialName,
            page: tablePage.currentPage,
            size: tablePage.pageSize,
            sort: 'sort,desc',
        }
        const data = await productList(params)
        gridOptions.loading = false
        gridOptions.data = data.records
        tablePage.total = data.total
    }
    catch (error) {
        gridOptions.loading = false
    }
}
findList()
function resetFormParams() {
    submitLoading.value = false
    state.value = {
        appId: '',
        banner: '',
        catId: '',
        code: '',
        creditLimit: 0,
        financialId: '',
        id: '',
        img: '',
        interestRate: 0,
        isDeleted: 0,
        linkType: '',
        linkUrl: '',
        name: '',
        remark: '',
        sort: 0,
        status: true,
        tag: '',
        type: '',
    }
}
function showForm(type: string, row?: any) {
    formType.value = type
    if (formType.value === formTypeEunm.edit) {
        state.value = {
            appId: row.appId,
            banner: row.banner,
            catId: row.catId,
            code: row.code,
            creditLimit: row.creditLimit,
            financialId: row.financialId,
            id: row.id,
            img: row.img,
            interestRate: row.interestRate,
            isDeleted: row.isDeleted,
            linkType: String(row.linkType),
            linkUrl: row.linkUrl,
            name: row.name,
            remark: row.remark,
            sort: row.sort,
            status: row.status === 1,
            tag: row.tag,
            type: String(row.type),
        }
    }

    centerDialogVisible.value = true
}
async function changeStatus(row: any) {
    try {
        console.log(row)
        const data = await updateStatusById(row.id)
        if (data === 1)
            ElMessage.success('修改成功')
        findList()
    }
    catch (error) {
    }
}
function formSubmit() {
    console.log(state.value)
    if (formType.value === formTypeEunm.add)
        addData()
    if (formType.value === formTypeEunm.edit)
        editData()
}
async function addData() {
    submitLoading.value = true
    try {
        const options: IAdd = {
            appId: state.value.appId,
            banner: state.value.banner,
            catId: state.value.catId,
            code: state.value.code,
            creditLimit: state.value.creditLimit ?? 0,
            financialId: state.value.financialId,
            img: state.value.img,
            interestRate: state.value.interestRate ?? 0,
            isDeleted: state.value.isDeleted,
            linkType: Number(state.value.linkType),
            linkUrl: state.value.linkUrl,
            name: state.value.name,
            remark: state.value.remark,
            sort: state.value.sort ?? 0,
            status: state.value.status ? 1 : 0,
            tag: state.value.tag,
            type: Number(state.value.type),
        }
        const data = await productAdd(options)
        if (data === 1)
            ElMessage.success('添加成功')
        centerDialogVisible.value = false
        findList()
    }
    catch (error) {
        submitLoading.value = false
    }
}
async function editData() {
    submitLoading.value = true
    try {
        const options: IEdit = {
            appId: state.value.appId,
            banner: state.value.banner,
            catId: state.value.catId,
            code: state.value.code,
            creditLimit: state.value.creditLimit ?? 0,
            financialId: state.value.financialId,
            id: state.value.id,
            img: state.value.img,
            interestRate: state.value.interestRate ?? 0,
            isDeleted: state.value.isDeleted,
            linkType: Number(state.value.linkType),
            linkUrl: state.value.linkUrl,
            name: state.value.name,
            remark: state.value.remark,
            sort: state.value.sort ?? 0,
            status: state.value.status ? 1 : 0,
            tag: state.value.tag,
            type: Number(state.value.type),
        }
        const data = await productEdit(options)
        if (data === 1)
            ElMessage.success('修改成功')
        centerDialogVisible.value = false
        findList()
    }
    catch (error) {
        submitLoading.value = false
    }
}
async function deleteRow(row: any) {
    console.log(row)
    try {
        await productDelete(row.id)
        ElMessage.success('删除成功')
        findList()
    }
    catch (error) {

    }
}
const configParams = ref(
    {
        configCode: '',
        configDesc: '',
        configInfo: '',
        configName: '',
        id: '',
    },
)
async function getConfig() {
    try {
        const data = await fsConfigGet({ configCode: 'product_sort' })
        console.log('🚀 ~ getConfig ~ data:', data)
        configParams.value = data
    }
    catch (error) {

    }
}
getConfig()
async function changeConfig() {
    console.log(configParams.value, 'configParams')
    try {
        await fsConfigUpdate(configParams.value)
        ElMessage.success('修改成功')
    }
    catch (error) {

    }
}
function search() {
    tablePage.currentPage = 1
    findList()
}
function reset() {
    searchForm.value = {
        catId: '',
        financialName: '',
    }
    findList()
}
function updateloading(val: boolean) {
    submitLoading.value = val
}
</script>

<template>
    <div class="mb-20 flex bg-white p-30">
        <div class="flex-1 pr-24">
            <PlusForm v-model="searchForm"
                      :columns="columns"
                      :row-props="{ gutter: 20 }"
                      label-width=""
                      :has-footer="false"
            />
        </div>

        <div class="">
            <ElButton type="primary"
                      @click="search"
            >
                搜索
            </ElButton>

            <ElButton @click="reset">
                重置
            </ElButton>
        </div>
    </div>

    <div class="bg-white p-30">
        <div class="mb-20 flex justify-between">
            <ElButton type="primary"
                      @click="showForm(formTypeEunm.add)"
            >
                {{ formTypeEunm.add }}
            </ElButton>

            <div>
                排序规则
                <el-radio-group v-model="configParams.configInfo"
                                class="ml-20"
                                @change="changeConfig"
                >
                    <el-radio value="auto"
                              size="large"
                    >
                        自动
                    </el-radio>

                    <el-radio value="manual"
                              size="large"
                    >
                        手动
                    </el-radio>
                </el-radio-group>
            </div>
        </div>

        <vxe-grid ref="xGrid"
                  v-bind="gridOptions"
        >
            <template #status="{ row }">
                <vxe-switch :model-value="row.status === 1"
                            @change="changeStatus(row)"
                />
            </template>

            <template #operate="{ row }">
                <ElButton @click="showForm(formTypeEunm.edit, row)">
                    {{ formTypeEunm.edit }}
                </ElButton>

                <ElButton @click="deleteRow(row)">
                    {{ formTypeEunm.destroy }}
                </ElButton>
            </template>

            <template #pager>
                <vxe-pager v-model:current-page="tablePage.currentPage"
                           v-model:page-size="tablePage.pageSize"
                           background
                           :total="tablePage.total"
                           :layouts="['Home', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
                           @page-change="handlePageChange"
                />
            </template>
        </vxe-grid>
    </div>

    <el-dialog v-model="centerDialogVisible"
               :title="dialogTitle"
               width="800"
               destroy-on-close
               align-center
               :close-on-click-modal="false"
               @close="resetFormParams"
    >
        <div class="max-h-500 of-auto pb-10">
            <EditForm :state="state"
                      :loading="submitLoading"
                      @close="centerDialogVisible = false"
                      @submit="formSubmit"
                      @updateloading="updateloading"
            />
        </div>
    </el-dialog>
</template>
